﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GridView的使用
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ViewState["SortDirection"] = "ASC";
                BindGridView("StudentID", "ASC");
            }
        }

        //public void BindGridView()
        //{
        //    SqlConnection connection = SqlHelper.GetConnection();
        //    DataSet dataSet = SqlHelper.GetDataSetBySqlCommand("SELECT * FROM Student", connection);

        //    gridStudent.DataSource = dataSet;
        //    Cache["DataSource"] = dataSet;
        //    gridStudent.DataBind();

        //    for (int i = 0; i < gridStudent.Rows.Count; i++)
        //    {
        //        gridStudent.Rows[i].Cells[0].Text = (i + 1).ToString();
        //    }
        //}
        public void BindGridView(string sortExpression, string sortDirection)
        {
            SqlConnection connection = SqlHelper.GetConnection();
            DataSet dataSet = SqlHelper.GetDataSetBySqlCommand("SELECT * FROM Student", connection);

            DataView dataView = dataSet.Tables[0].DefaultView;
            dataView.Sort = sortExpression + " " + sortDirection;
            gridStudent.DataSource = dataView;
            Cache["DataSource"] = dataView;


            gridStudent.DataBind();

            for (int i = 0; i < gridStudent.Rows.Count; i++)
            {
                gridStudent.Rows[i].Cells[0].Text = (i + 1).ToString();
            }
        }

        protected void gridStudent_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridStudent.PageIndex = e.NewPageIndex;
            //BindGridView(gridStudent.SortExpression, ViewState["SortDirection"].ToString());
        }

        protected void gridStudent_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortDirection = ViewState["SortDirection"].ToString();

            if (sortDirection == "ASC")
            {
                ViewState["SortDirection"] = "DESC";
            }
            else if (sortDirection == "DESC")
            {
                ViewState["SortDirection"] = "ASC";
            }

            BindGridView(e.SortExpression, ViewState["SortDirection"].ToString());
        }
    }
}